package cs419.magnusmi.trackitcs;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class addDetail extends Activity {


    //async variable
    private ItemAddTask iAddTask = null;

    Button cancelBtn;
    SQLiteDatabase db;

    // UI references.
    private String id;
    private TextView idView;
    private EditText namePrompt;
    private EditText serialPrompt;
    private EditText pagesPrompt;
    private EditText accessoriesPrompt;
    private EditText operatingSystemPrompt;
    private EditText specialFeaturesPrompt;
    private EditText otherInfoPrompt;
    private String sqltId;
    private String sqltName;
    private String sqltSerial;
    private String sqltPages;
    private String sqltAccessories;
    private String sqltOs;
    private String sqltSpecialFeatures;
    private String sqltOtherInfo;

    //for progress display
    private View mAddDetailView;
    private View mAddDetailStatusView;
    private TextView mAddDetailStatusMessageView;

    //session variables
    String user;
    String API;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_detail);


        db=openOrCreateDatabase("MyDB1",MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS ProjItems(id VARCHAR, name VARCHAR, serial VARCHAR, pages VARCHAR,accessories VARCHAR,os VARCHAR,specialFeats VARCHAR,otherInf VARCHAR);");


        //get ID just entered
        Intent start = getIntent();
        id = start.getStringExtra("newItemID");

        //session vars
        user = start.getStringExtra("user");
        API = start.getStringExtra("API");

        //setup add form
        idView = (TextView) findViewById(R.id.idView);
        idView.setText(id);
        namePrompt = (EditText) findViewById(R.id.itemName);
        serialPrompt = (EditText) findViewById(R.id.serialNum);
        pagesPrompt = (EditText) findViewById(R.id.pages);
        accessoriesPrompt = (EditText) findViewById(R.id.accessories);
        operatingSystemPrompt = (EditText) findViewById(R.id.operatingSystem);
        specialFeaturesPrompt = (EditText) findViewById(R.id.specialFeatures);
        otherInfoPrompt = (EditText) findViewById(R.id.otherInfo);

        //setup progress bar
        mAddDetailView = findViewById(R.id.addDetail_form);
        mAddDetailStatusView = findViewById(R.id.addDetail_status);
        mAddDetailStatusMessageView = (TextView) findViewById(R.id.addDetail_status_message);

        //on click, begin login
        findViewById(R.id.addDetailBtn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        //on cancel, return to inventory
        cancelBtn = (Button) findViewById(R.id.cancelBtn2);
        cancelBtn.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                //Launching add Activity
                Intent i = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(i, user, API);
                startActivity(i);
            }
        });
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Show the Up button in the action bar.
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu)  {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.logout:
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //clear stack to enforce logout (http://stackoverflow.com/questions/3007998/on-logout-clear-activity-history-stack-preventing-back-button-from-opening-l)
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                return true;
            case R.id.inventory_menu:
                Intent j = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(j, user, API);
                startActivity(j);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (iAddTask != null) {
            return;
        }

        // Reset errors.
        namePrompt.setError(null);
        serialPrompt.setError(null);
        pagesPrompt.setError(null);
        accessoriesPrompt.setError(null);
        specialFeaturesPrompt.setError(null);
        operatingSystemPrompt.setError(null);
        otherInfoPrompt.setError(null);

        // Store values at the time of the login attempt.

        Item newItem = new Item(id, namePrompt.getText().toString(), serialPrompt.getText().toString(),
                pagesPrompt.getText().toString(), accessoriesPrompt.getText().toString(),
                operatingSystemPrompt.getText().toString(), specialFeaturesPrompt.getText().toString(), otherInfoPrompt.getText().toString());


        //validate form
        boolean cancel = false;

        //array of Views to highlight any invalid input
        View[] focusViews = new View[3];
        for (int i = 0; i < focusViews.length; i++){
            focusViews[i] = null;
        }

        //check for name entry (required)
        if (TextUtils.isEmpty(newItem.getName())) {
            namePrompt.setError(getString(R.string.error_field_required));
            focusViews[0] = namePrompt;
            cancel = true;
        }

        // Check for serial entry (required)
        if (TextUtils.isEmpty(newItem.getSerial())) {
            serialPrompt.setError(getString(R.string.error_field_required));
            focusViews[1] = serialPrompt;
            cancel = true;
        }
        String pages = newItem.getPages();
        if (!(TextUtils.isEmpty(pages)) && pages != "N/A"){
            try{
                int i = Integer.parseInt(pages);
            }
            catch (NumberFormatException e){
                cancel = true;
                pagesPrompt.setError(getString(R.string.number_format_improper));
                focusViews[2] = pagesPrompt;
            }
        }


        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            // set focus to first field.  Others are clickable
            for (int i = 0; i < focusViews.length; i++){
                if (focusViews[i] != null){
                    focusViews[i].requestFocus();
                    break;
                }
            }
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mAddDetailStatusMessageView.setText(R.string.ItemAddAttempt);
            showProgress(true);
            iAddTask = new ItemAddTask();
            iAddTask.execute(newItem);
			
			//add items to the SQLite db
	        sqltId = id;
			sqltName = namePrompt.getText().toString();
			sqltSerial = serialPrompt.getText().toString();
			sqltPages = pagesPrompt.getText().toString();
			sqltAccessories = accessoriesPrompt.getText().toString();
			sqltOs = operatingSystemPrompt.getText().toString();
			sqltSpecialFeatures = specialFeaturesPrompt.getText().toString();
			sqltOtherInfo = otherInfoPrompt.getText().toString();

			//how to handle the insert into the sqlite database
			db.execSQL("INSERT INTO ProjItems VALUES('"+sqltId+"','"+sqltName+"','"+sqltSerial+"','"+sqltPages+"','"+sqltAccessories+"','"+sqltOs+"','"+sqltSpecialFeatures+"','"+sqltOtherInfo+"');");


        }
    }




    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mAddDetailStatusView.setVisibility(View.VISIBLE);
            mAddDetailStatusView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 1 : 0)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mAddDetailStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                        }
                    });

            mAddDetailView.setVisibility(View.VISIBLE);
            mAddDetailView.animate()
                    .setDuration(shortAnimTime)
                    .alpha(show ? 0 : 1)
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            mAddDetailView.setVisibility(show ? View.GONE : View.VISIBLE);
                        }
                    });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mAddDetailStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mAddDetailView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class ItemAddTask extends AsyncTask<Item, Void, Boolean> {
        private String response = "";


        @Override
        protected Boolean doInBackground(Item... items) {
            //PHP to add new item
            String registerItem = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/newItem";
            Item newItem = items[0];

            //create array list of name value pairs and perform http POST
            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("id", newItem.getId()));
            parameters.add(new BasicNameValuePair("name", newItem.getName()));
            parameters.add(new BasicNameValuePair("serial", newItem.getSerial()));
            parameters.add(new BasicNameValuePair("accessories", newItem.getAccessories()));
            parameters.add(new BasicNameValuePair("specialFeatures", newItem.getSpecialFeatures()));
            parameters.add(new BasicNameValuePair("operatingSystem", newItem.getOperatingSystem()));
            parameters.add(new BasicNameValuePair("pages", newItem.getPages()));
            parameters.add(new BasicNameValuePair("otherInfo", newItem.getOtherInfo()));

            JSONObject json = jsonParser.makeHttpRequest(registerItem, "POST", parameters);

            Boolean errors;
            try{
                response = json.getString("message");
                errors = json.getBoolean("error");
            }
            catch (JSONException e) {
                errors = true;
            }

            return errors;
        }

        /**
         * post-execution method to print results and either cancel or return
         * @param errors
         */
        @Override
        protected void onPostExecute(final Boolean errors) {
            iAddTask = null;
            showProgress(false);

            boolean success = !errors;  //no errors = success

            if (success) {
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, response, duration);
                toast.show();
                Intent i = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(i, user, API);
                startActivity(i);
            } else {
                Context context = getApplicationContext();
                int duration = Toast.LENGTH_LONG;
                Toast toast = Toast.makeText(context, response, duration);
                toast.show();
            }
        }

        /**
         * cancel method
         */
        @Override
        protected void onCancelled() {
            iAddTask = null;
            showProgress(false);
        }
    }

}
